package com.meevle.utilities;

import java.sql.Timestamp;
import java.util.Date;

import com.meevle.dao.SlotCommentDAO;
import com.meevle.dao.SlotDAO;
import com.meevle.dao.UserDAO;
import com.meevle.vo.SlotCommentVO;

public class VoToDAoAdapter {

	private volatile static VoToDAoAdapter instance = null;
	
	private VoToDAoAdapter()
	{}
	
	public static VoToDAoAdapter getInstance () {
        if (instance == null)
        {
        	synchronized (VoToDAoAdapter.class)
        	{
        		if (instance == null) instance = new VoToDAoAdapter();
			}
        }
        return instance;
    }
	
	/**
	 * Transforms a TrackCommentVO into an TrackCommentDAO object. While doing so, it check if the Track and the user 
	 * actually do exist in the database. If not => IllegalArgumentException
	 * 
	 * @param commentVo
	 * @return
	 * @throws IllegalArgumentException If the commentVO.Track or the commentVO.User don't exist
	 * @throws Exception If something went wrong during the database access
	 */
	public SlotCommentDAO getSlotCommentDAOFromSlotCommentVO(SlotCommentVO commentVo, boolean createTimestamp)throws IllegalArgumentException, Exception
	{
		SlotCommentDAO commentDao = new SlotCommentDAO();
		
		try {
			commentDao.setSlot(SlotDAO.getSlot(commentVo.getSlot()));
			commentDao.setAuthor(UserDAO.getUser(commentVo.getAuthor()));
				//Takes care of the escaping of HTML code
			commentDao.setComment(ProcessBBcodeJava.getInstance().preparePostText(commentVo.getComment() ) );
			commentDao.setRating(commentVo.getRating());
			commentDao.setTimestamp( (createTimestamp?new Date(System.currentTimeMillis()):commentVo.getTimeStamp() ) );
			commentDao.setComment(commentVo.getComment());
			commentDao.setRating(commentVo.getRating());
			
				//timestamp is set here...
			commentDao.setTimestamp(new Timestamp(System.currentTimeMillis()));
		} catch (IllegalArgumentException e) {
			throw e;
		} catch (NullPointerException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("None of the following fields of a TrackComment can be null: The track, the author, the comment and the rating");
		} catch (Exception e) {
			throw e;
		}
		
		
		
		return commentDao;
	}
}
